package com.hzw.core.weiget

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.graphics.drawable.RippleDrawable
import android.util.AttributeSet
import android.widget.LinearLayout
import androidx.annotation.CallSuper
import androidx.annotation.RequiresApi
import com.hzw.core.R
import com.hzw.core.resources.styledColorSL
import com.hzw.core.resources.styledDrawable

/**
 * 触摸带水波纹的LinearLayout
 */
@SuppressLint("Recycle", "CustomViewStyleable")
open class SelectableLinearLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet?, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    constructor(context: Context) : this(context, null)

    var foregroundSelector: Drawable? = null
        set(value) {
            field?.callback = null
            field = value
            value?.callback = this
            setWillNotDraw(value === null)
        }

    init {
        val colorSl: ColorStateList?
        context.obtainStyledAttributes(attrs, R.styleable.SelectableLinearLayout).apply {
            try {
                colorSl = getColorStateList(R.styleable.SelectableLinearLayout_ll_rippleTint)
            } finally {
                recycle()
            }
        }
        val drawable = styledDrawable(android.R.attr.selectableItemBackground)
        if (drawable is RippleDrawable && colorSl != null) {
            drawable.setColor(colorSl)
        }
        foregroundSelector = drawable
    }

    @CallSuper
    override fun drawableStateChanged() {
        super.drawableStateChanged()
        foregroundSelector?.state = drawableState
    }

    @CallSuper
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        foregroundSelector?.setBounds(0, 0, w, h)
    }

    @CallSuper
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        foregroundSelector?.draw(canvas)
    }

    @CallSuper
    override fun jumpDrawablesToCurrentState() {
        super.jumpDrawablesToCurrentState()
        foregroundSelector?.jumpToCurrentState()
    }

    @CallSuper
    override fun verifyDrawable(who: Drawable): Boolean {
        return who === foregroundSelector || super.verifyDrawable(who)
    }

    @RequiresApi(21)
    @CallSuper
    override fun dispatchDrawableHotspotChanged(x: Float, y: Float) {
        super.dispatchDrawableHotspotChanged(x, y)
        foregroundSelector?.setHotspot(x, y)
    }
}
